<?php
require_once "includes/pagination.php";
require_once "includes/class/member_management.class.php";
require_once('AmazonAPI/.config.inc.php');
require_once('AmazonAPI/CBUI/CBUIRecipientTokenPipeline.php');

$itemPerPage=10;
if($_SESSION['user_id_sess']=="") {
	echo "<script type='text/javascript'> window.location='index.php?signin&url=mylist'; </script>";
}
$userId = $_SESSION['user_id_sess'];
$ss = mysql_query("select googleMapKey from tbl_settings where setting_id=1") or die(mysql_error());
$tbl_settings = mysql_fetch_array($ss);
if($tbl_settings) $googleMapKey = $tbl_settings['googleMapKey'];  else $googleMapKey='';
	
$sql_user="Select * from tbl_users where user_id='".$_SESSION['user_id_sess']."'";
$res_user=mysql_query($sql_user);
$row_user=mysql_fetch_array($res_user);
$tokenID=$row_user['comm_tokenID'];

$address_of_user	= getUserAddress($_SESSION['user_id_sess']);
 
if(isset($_REQUEST['signature']) && !empty($_REQUEST['signature'])) {
	$signature = $_REQUEST['signature'];
	$refundTokenID = $_REQUEST['refundTokenID'];
	$signatureVersion = $_REQUEST['signatureVersion'];
	$signatureMethod = $_REQUEST['signatureMethod'];
	$certificateUrl = $_REQUEST['certificateUrl'];
	$tokenID = $_REQUEST['tokenID'];
	$callerReference = $_REQUEST['callerReference'];
	$sqlUpdUsr = "UPDATE tbl_users SET comm_signature='".$signature."',
				comm_refundTokenID='".$refundTokenID."',
				comm_signatureVersion='".$signatureVersion."',
				comm_signatureMethod='".$signatureMethod."',					
				comm_certificateUrl='".$certificateUrl."',
				comm_tokenID='".$tokenID."',
				comm_callerReference='".$callerReference."' WHERE user_id='$userId'";
	$rstUpdUsr = mysql_query($sqlUpdUsr) or die(mysql_error());
	if($rstUpdUsr) { 
		$msg = "Your tokenID is successfully set.";
	}else{
		$msg = "Your tokenID is not set please try again!";
	}
}


if($tokenID=='')
{
	/*$pipeline = new Amazon_FPS_CBUIRecipientTokenPipeline(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY);
	$pipeline->setMandatoryParameters("swapen".rand(),  
			H_ROOT."index.php?addProduct", "0", "0.0", "True");
	//optional parameters
	$pipeline->addParameter("paymentMethod", "CC");
	$re_URL = $pipeline->getUrl();
	header("location:".$re_URL);*/
	
	echo "<script type='text/javascript'> window.location='index.php?amazon_land'; </script>";
}

$search_string= '';
$pro_category = '';
$pro_subcategory = '';
$srch_cond = '';
if(isset($_REQUEST['srch']))
{
	$search_string 		= $_REQUEST['search_string'];
	$pro_category		= $_REQUEST['pro_category'];
	$pro_subcategory	= $_REQUEST['pro_subcategory'];
	
	if($search_string!='')
		$srch_cond.=" AND product_name like '%".$search_string."%' ";
	if($pro_category!='')
		$srch_cond.=" AND category_id IN (SELECT category_id FROM tbl_category where parent_id=$pro_category) ";
	if($pro_subcategory!='')
		$srch_cond.=" AND category_id=$pro_subcategory";
		
	
}


//delete single product		 
if(!empty($_POST['hidDelPro'])) {

	$proId=$_POST['hidDelPro'];
	$sqlDelPro="Delete from tbl_product where product_id=$proId";
	$rstDelPro=mysql_query($sqlDelPro);
	if($rstDelPro) { 
		$imgPaths=getImagePath($proId);
		if($imgPaths[0]!="") { unlink($imgPaths[0]); }
		if($imgPaths[1]!="") { unlink($imgPaths[1]); }
		if($imgPaths[2]!="") { unlink($imgPaths[2]); }
		echo "<div id='suc-msg'> Your product deleted. </div><br>"; 
	}	
	else {
		echo "<div id='err-msg'> Your product could not be deleted. </div><br>";
	}
}			
   
?>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=true&amp;oe=utf-8&amp;key=<?php echo $googleMapKey; ?>" type="text/javascript"></script>
<div id="panel" style="width:950px;">
	<table>
		<tr>
			<td colspan="2" valign="top">	
				<div style="width: 950px; float: left; vertical-align: top; margin:15px 0px 5px 0px;">
					<a href="javascript:void(0);" class="yellow_btn" style="float:right; text-decoration:none; cursor:help;">Regularly the higher the commission the more you earn per sale<br />
					Regularly the lower the commission the more often you sell</a>
					<font class="grey_big" style="float:right; margin:7px 10px 0px 0px;">Pro Tips</font>
				</div>
					
				<div style="width: 950px; float: left; margin:10px 0px 5px 0px;">
				
					<div class="mypg_left_out">		
						<a href="#"><img src="images/arrow_back.png" style="border:none; margin:0px 5px 0px 0px;" />Back to Search Results</a>		
					</div>
					
					<div class="fullbox_out">	
						<strong class="orangehead">Choose Products to Sell</strong>
						<p style="margin: 5px 0px;" class="grey_txt">
							<i>Sell products for business or people and earn a commission. You choose the item with the best price and commission.</i>
						</p>	
					</div>
				
				</div>
			</td>
		</tr>
	</table>
	
	<table width="100%" border="0">
		<tr>
			<td>
				<div style="width: 950px; float: left; vertical-align: top;">
					<div class="mypg_left_out">
						<table style="width:100%">
							<tr>
								<td width="214" valign="top">
									<p style="color:#767676; font-size: 14px; font-weight: normal; margin:5px 0px 5px 0px;">
										Refine Search
									</p>
									<div class="shourtbox">
										<table border="0" width="100%">
										<tbody>
											<tr>
												<td>
													<form id="formShopSearch" name="formShopSearch" method="post" action="">
													<table cellspacing="0" cellpadding="0" border="0" width="212">
													<tbody>
														<tr>
															<td style="vertical-align: top;">
																<div id="category-title">Search Within Store</div>
																<br>
																<div class="fulldiv">
																	<center>
																	
																		<input type="text" style="width: 120px; float: left;" class="inputbg" id="search_string" name="search_string" value="<?php echo $search_string;?>" />
																		<input type="submit" style="height: 30px; margin: 0px 0px 0px 10px;" class="yellow_btn" value="Search" name="search" onclick="javascript:$('#srch').val('1');" />
																	
																	</center>
																</div>
															</td>
														</tr>
		  
														<tr>
															<td style="vertical-align: top;"><br>
																<div id="category-title">Category</div>
																<br>
	  
																
																
																<select onchange="getsubsearch(this.value);" class="inputbg" id="pro_category" name="pro_category" style="width:200px;">
																	<?php echo get_category_all(1); ?>
																</select>
																
																<script>$('#pro_category').val(<?php echo $pro_category;?>);</script>
	 
															</td>
														</tr>
			   
														<tr>
															<td style="vertical-align: top;"><br>
																<div id="category-title">Sub-Category</div>
																<br>
	  
																
																<select onchange="javascript:var x=document.getElementById('formShopSearch'); x.submit();" class="inputbg" id="pro_subcategory" name="pro_subcategory" style="width:200px;">
																	
																	<?php
																	if($pro_category!='') echo get_category_all($pro_category); else echo '<option selected="selected" value="">Select Sub-Category..</option>'; 
																	?>
																</select>
																<script>$('#pro_subcategory').val(<?php echo $pro_subcategory;?>);</script>
																<br> <br>
	 
															</td>
														</tr>
														
														<tr>
															<td style="vertical-align: top;">
																<div id="category-title">By Price</div>
																<p><a href="index.php?addProduct<?php echo $pagelink; ?>&pricebtw=1">under - $10</a></p>  
																<p><a href="index.php?addProduct<?php echo $pagelink; ?>&pricebtw=2">$10 - $50</a></p>  
																<p><a href="index.php?addProduct<?php echo $pagelink; ?>&pricebtw=3">$50 - $100</a></p>  
																<p><a href="index.php?addProduct<?php echo $pagelink; ?>&pricebtw=4">$100 - $500</a></p> 
																<p><a href="index.php?addProduct<?php echo $pagelink; ?>&pricebtw=5">$500 +</a></p>           
																 </td>
														</tr>
      
													</tbody>
													</table>
													<input type="hidden" name="srch" id="srch" />
													</form>
												</td>
											</tr>
										</tbody>
										</table>
									</div>
								</td>
							</tr>
						</table>
					</div>
					<!--end:mypg_left_out-->
					
					<div class="fullbox_out">
						<table style="width: 100%;">
						<tbody>
							<tr>
								<td>
									<div id='panel' style="border:none; width:700px;">
										<strong class="orangehead">Search Results <?php if(!empty($searchFor)) echo " - ".$searchFor; ?></strong>
										<?php
										$bm =$local=$online='';
										if($_GET['sortby']=='' || $_GET['sortby']=='bm')
											$bm = 'style="font-weight:bold;"';
										else if($_GET['sortby']=='online')
											$online = 'style="font-weight:bold;"';
										else if($_GET['sortby']=='local')
											$local='style="font-weight:bold;"';
										?>
										<div class="fulldiv" style="margin: 10px 0px 0px;">
											<table align="center" width="100%" border="0">
												<tr>
													<td width="15%">Sort Options:</td>
													<td width="15%"><a href="index.php?addProduct<?php echo $pagelink; ?>&sortby=bm" <?php echo $bm;?>>Best Match</a></td>
													<td width="15%"><a href="index.php?addProduct<?php echo $pagelink; ?>&sortby=online" <?php echo $online;?>>Online only</a></td>
													<td width="15%"><a href="index.php?addProduct<?php echo $pagelink; ?>&sortby=local" <?php echo $local;?>>Local Only</a></td>
													<td width="30%">
													
														<div class="greytab_out" style="margin:0px 5px -9px 5px;">
															<div class="greytab_left">&nbsp;</div>
															<div class="greytab_repeat" style="cursor:pointer;" onclick="window.location='index.php?addProduct<?php echo $pagelink; ?>&sortby=comison'">Sort price &amp; Commission</div>
															<div class="greytab_right">&nbsp;</div>
</div>
			
													</td>
												</tr>
											</table>
										</div>
										
										
										<form name="frmProlist" id="frmProlist" method="post" action="">
											<input type="hidden" name="hidDelPro" id="hidDelPro">
											<?php
												
											
												$sqlSelPro="SELECT * FROM tbl_product where posted_by!='$userId' AND sell_by=0 $srch_cond";
												
												$sqlSelPro.=" AND posted_by IN (select user_id from tbl_users where tbl_users.status='1') ";
												if(!empty($_GET['pricebtw']))
												{
													
													if($_GET['pricebtw']=='1')
													{
														$sqlSelPro.=" AND product_price < 10";
													}
													else if($_GET['pricebtw']=='2')
													{echo "hello".$_GET['pricebtw'];
														$sqlSelPro.=" AND product_price >= 10 AND product_price <= 50";
													}
													else if($_GET['pricebtw']=='3')
													{
														$sqlSelPro.=" AND product_price >= 50 AND product_price <= 100";
													}
													else if($_GET['pricebtw']=='4')
													{
														$sqlSelPro.=" AND product_price >= 100 AND product_price <= 500";
													}
													else if($_GET['pricebtw']=='5')
													{
														$sqlSelPro.=" AND product_price >500";
													}
												}
												//echo $sqlSelPro;
												if(!empty($_GET['sortby'])) {
													if($_GET['sortby']=='lps') {
														$sqlSelPro .= " order by product_price ASC, shipping ASC";		
													}
													else if($_GET['sortby']=='hps') {
														$sqlSelPro .= " order by product_price DESC, shipping DESC";		
													}
													else if($_GET['sortby']=='bm') {
														$sqlSelPro .= " order by field(product_name, '$key') DESC";		
													}
													else if($_GET['sortby']=='online') {
														$sqlSelPro .= " order by field(selling_type, 'online') desc";		
													}
													else if($_GET['sortby']=='local') {
														$sqlSelPro .= " order by field(selling_type, 'local') desc";		
													}
													
													else if($_GET['sortby']=='comison') {
														$sqlSelPro .= " ORDER BY commission DESC";		
													}
													      
													      $sqlSelPro .=", posted_date DESC";	
												}
												else
												{ 
													$sqlSelPro .=" ORDER BY posted_date DESC";	
												}
												//echo $sqlSelPro;
												$rstSelPro=mysql_query(getPagingQuery($sqlSelPro,$itemPerPage));				  
												$num=mysql_num_rows($rstSelPro);
						   
												if($num==0)
												{
													echo "<div style='border-top:1px solid #CCCCCC;'> </div><br>";
													echo "<p style='padding:5px;'>No products found for sale...</p><br>";
													echo "<div style='border-top:1px solid #CCCCCC;'> </div><br>";
												}
												else {
													$r=1;
													while($rowSelPro=mysql_fetch_array($rstSelPro))
													{
														if($rowSelPro['quantity']!='0') {
														$productId=$rowSelPro['product_id'];
														$productName=wordFormater($rowSelPro['product_name'],12);
														$productTitle = $rowSelPro['product_name'];					   
														$productPrice=$rowSelPro['product_price'];
														$productThumb=$rowSelPro['product_thumbnail'];
														$productImage=$rowSelPro['product_image'];
														$productSellingType=$rowSelPro['selling_type'];
														$productShipping=$rowSelPro['shipping'];
														$productProCondition=$rowSelPro['pro_condition'];
														$productQuantity=$rowSelPro['quantity'];
														$commission=$rowSelPro['commission'];
														$postedBy=$rowSelPro['posted_by'];
														$postedDate=$rowSelPro['posted_date'];
														$localPickup=$rowSelPro['localPickup'];
														$bargainDate = $rowSelPro['bargain_duration'];
														if(!empty($productShipping))
															$productShipping=number_format($productShipping,2);
														else
															$productShipping="Free";
														$timeLeft = getRemainingTime($bargainDate);
														$ownerType = getUserType($postedBy);
														$utype  =   getUserType($postedBy);
														$ownerName = getUser_first_name($postedBy);
														
														$pimage = getProductImage($productId,'p');
														if($pimage['thumb']!="") {
															     $productThumb = $pimage['thumb'];
														} else {
															     $productThumb="images/no_image.gif";	
														}
														
														if($ownerType=='1')
															$ownerType="i.png";
														else if($ownerType=='2' || $ownerType=='4')
															$ownerType="s.png";
														else if($ownerType=='3')
															$ownerType="m.png";
														     
														if($timeLeft < 0) {
															$timeLeft = "<font color='red'>Listing Expired</font>";
														}
														
														$address_of_seller= getUserAddress($postedBy);
														?>
														<input type="hidden" name="address_of_seller" value="<?php echo $address_of_seller;?>" id="address_of_seller<?php echo $productId;?>" />
														<input type="hidden" name="address_of_user" value="<?php echo $address_of_user;?>" id="address_of_user" />
														<input type="hidden" name="lat<?php echo $productId;?>" value="" id="lat<?php echo $productId;?>" />
														<input type="hidden" name="lon<?php echo $productId;?>" value="" id="lon<?php echo $productId;?>" />
								
														<script type="text/javascript">
														var geocoder, location1, location2, gDir;
													       	geocoder = new GClientGeocoder();
														gDir = new GDirections();
														
														var address_of_seller = $('#address_of_seller<?php echo $productId;?>').val();
														geocoder.getLocations(address_of_seller, function (response) {
															if (!response || response.Status.code != 200)
															{
																//alert("Sorry, we were unable to geocode the first address");
															}
															else
															{
																
																
																location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
																
																$('#lat<?php echo $productId;?>').val(response.Placemark[0].Point.coordinates[1]);
																$('#lon<?php echo $productId;?>').val(response.Placemark[0].Point.coordinates[0]);
																
																var address_of_user = $('#address_of_user').val();
																geocoder.getLocations(address_of_user, function (response) {
																	if (!response || response.Status.code != 200)
																	{
																		//alert("Sorry, we were unable to geocode the second address");
																	}
																	else
																	{ 
																		location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
																		gDir.load('from: ' + location1.address + ' to: ' + location2.address);
																	}
																
																	
																});
															}
														});
														
														GEvent.addListener(gDir, "load", function() {
															var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
															var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
															//document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Driving Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + drivingDistanceKilometers + ' kilometers)';
															var result = drivingDistanceMiles.toFixed(2);
															$('#distance').html('<i>miles away - </i><br /><font style="color:#000000;">'+result+' miles</font> <br />');
														});
														</script>
														<!--start-->
														<div class="fulldiv">
															<div class="fullbox_top"></div>
								
															<div class="fullbox_repeat">
																<div class="sellpro_table">
																	<div class="sellpro_row1">
																		<img src='<?php echo $productThumb; ?>' />
																	</div>
																	
																	<div class="sellpro_row2">
																		<p class="sellpro_head" style="margin:5px 0px 5px 0px;">
																		<a href="index.php?SellProduct=<?php echo $productId;?>" class="sellpro_head" title="<?php echo $productTitle; ?>"> <?php echo $productName; ?> </a>
																		</p>
																		<i>product owner - <?php echo $ownerName;?></i><br>
																		<i>local pick up - <font style="color:#000000;"><?php if($localPickup==1) echo 'available'; else echo 'not available'; ?></font></i>
																	</div>
																	
																	<div class="sellpro_row3" style="text-align:center;">
																		    <img src="images/<?php echo $ownerType;?>" <?php if($utype=='3') { ?> alt="Verified Merchant" title="Verified Merchant" <?php } ?> />
																		<p style="font-size:12px;">
																			<span id="distance"></span>&nbsp;
																			<font style="color:#000000;">(<a class="bluelink" href="javascript:void(0)" onclick="show_map(<?php echo $productId?>)">map it</a>)</font>
																		</p>
																	</div>
																	
																	<div class="sellpro_row2" style="text-align:right; font-size:12px;">
																		<p class="redtxt" style="margin:5px 0px 5px 0px; font-size:12px;">
																			$<?php echo number_format($productPrice,2);?> +<font style="color:#000000;"> $<?php echo $productShipping;?> S &amp; h</font>
																		</p>
																		<?php if($_SESSION['user_type_sess']!=2) { ?>
																		<p style="margin:5px 0px 5px 0px;">Bargain:<i>Commission-$<?php echo number_format($commission,2);?></i></p>
																		<?php } ?>
																		<p style="margin:5px 0px 5px 0px;">
																		<a href="index.php?SellProduct=<?php echo $productId;?>" style="font-size:14px; font-weight:bold;">ADD TO STORE</a>
																		</p>
																	</div>
																</div>
															</div>
															
															<div class="fullbox_bot"></div>
														</div>
														<!--end-->
											<?php
											}
													}//while
												}//else
											
											?>
											<div align="center" class="fulldiv" style="text-align:center;"><?php
												//$link="addProduct";
												//echo $sqlSelPro;
												$link="addProduct&".$pagelink;
												echo $disp=getPagingLink($sqlSelPro,$itemPerPage,$link);							   
										      ?></div>
										</form>
									</div>
								</td>
							</tr>
						</tbody>
						</table>
					</div>
					
				</div>
				<!--950 end-->	
			</td>
		</tr>
	</table>
</div>
<script>
function show_map(pid)
{
  // var pos = $('#more_info_link').position();
  var ntop = ( $(window).height() - $('#map_box').height() ) / 2+$(window).scrollTop();
  var nleft = ( $(window).width() - $('#map_box').width() ) / 2+$(window).scrollLeft();
  
  $('#map_box').css({'left': nleft, 'top':ntop});
  $('#map_box').show();
  var lat = $('#lat'+pid).val();
  var lon = $('#lon'+pid).val();
  //alert(lat+' '+lon);
  initialize(lat,lon);
 
  
}



function initialize(lat,lon) {
  if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(new GLatLng(lat, lon), 13);
    var latlng = new GLatLng(lat,lon);
    map.addOverlay(new GMarker(latlng));
    
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
  }
}

function getsubsearch(category_id)
{
	var url = "<?php echo $base_url;?>ajax_category_option.php";
	$.post(url,
	{ 'category_id':category_id},
	function(data)
	{
		$('#pro_subcategory').html(data);
	},
	'html');
	
	var x=document.getElementById("formShopSearch");
	x.submit();
}

</script>
<div id="map_box" style="position:absolute; width:650px; height:470px; background:#000000; display:none;" align="center">
 <span style="float:right; color:#fff; padding:10px; font-weight:bold; cursor:pointer;" onclick="$('#map_box').hide();">x</span><br />
 <div id="map_canvas" style="width: 600px; height: 400px"></div>
</div>


